package com.tarena.lbs.user.controller;

import com.tarena.lbs.common.encoder.JwtEncoder;
import com.tarena.lbs.common.utils.JsonUtils;
import com.tarena.lbs.user.config.WechatMiniAppConfig;
import com.tarena.lbs.user.pojo.dto.LoginSuccessResponse;
import com.tarena.lbs.user.pojo.dto.WechatLoginRequest;
import com.tarena.lbs.user.pojo.dto.WechatLoginResponse;
import com.tarena.lbs.user.pojo.po.UserPO;
import com.tarena.lbs.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.base.protocol.exception.BusinessException;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Slf4j
public class WechatAuthController {

    private final WechatMiniAppConfig wechatConfig;
    private final UserService userService;
    private final JwtEncoder jwtTokenService;

    @PostMapping("/wechat/login")
    public ResponseEntity<?> wechatLogin(@RequestBody WechatLoginRequest request) {
        String code = request.getCode();
        if (code == null || code.trim().isEmpty()) {
            return ResponseEntity.badRequest().body("code is required");
        }

        // 1. 调用微信接口换取 openid
        String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                wechatConfig.getAppId(),
                wechatConfig.getAppSecret(),
                code
        );

        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        WechatLoginResponse wxResp = JsonUtils.fromJson(response, WechatLoginResponse.class);

        if (wxResp.getErrcode() != null && wxResp.getErrcode() != 0) {
            log.error("微信登录失败: errcode={}, errmsg={}", wxResp.getErrcode(), wxResp.getErrmsg());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid code or wechat error: " + wxResp.getErrmsg());
        }

        if (wxResp.getOpenid() == null) {
            log.error("微信登录失败: {}", response);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid code or wechat error");
        }

        String openid = wxResp.getOpenid();
        // String sessionKey = wxResp.getSessionKey(); // 仅当需要解密手机号时使用

        // 2. 查询或创建本地用户
        UserPO user = userService.findByOpenid("wechat_mini", openid);
        if (user == null) {
            user = userService.createWechatMiniUser(openid);
            // 可返回标志位，让前端跳转"完善资料"页面
        }

        // 3. 生成 JWT
        UserPrinciple userPrinciple = new UserPrinciple();
        userPrinciple.setId(user.getId());
        userPrinciple.setNickname(user.getNickName());
        userPrinciple.setRole(Roles.USER);
        
        String token;
        try {
            token = jwtTokenService.generateToken(userPrinciple);
        } catch (BusinessException e) {
            log.error("生成JWT失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Token生成失败");
        }

        return ResponseEntity.ok(new LoginSuccessResponse(token, user));
    }
}

